package cn.wzr.controller;

import cn.wzr.dao.impl.CommodityDao;
import cn.wzr.entity.Commodity;
import cn.wzr.global.Const;
import cn.wzr.util.CommonTools;
import cn.wzr.util.upload.UploadValidImage;
import org.json.simple.JSONObject;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Collection;

import static cn.wzr.util.CommonTools.isPositiveInt;

@MultipartConfig
@WebServlet(Const.WEBURL_SEPARATOR + Const.ACT_MULTIMG_UPLOAD)
public class MultiCmdtImgsUpload extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String contextPath = getServletContext().getRealPath(String.valueOf(Const.WEBURL_SEPARATOR));

        JSONObject resultJson = new JSONObject();
        String imgUCPerCmdtStr = request.getParameter("imgUploadCountPerCmdt");
        int imgUCPerCmdt;   // 每件商品图片数量
        if (!isPositiveInt(imgUCPerCmdtStr)) {
            resultJson.put(Const.JS_P_ERRINFO, "传入的'每件商品图片数量'为非正整数值.");
            PrintWriter out = response.getWriter();
            out.print(resultJson.toJSONString());
            return;
        } else {
            imgUCPerCmdt = Integer.parseInt(imgUCPerCmdtStr);
        }
/*
        try {
            request.setCharacterEncoding(Const.ENCODING);
        } catch (UnsupportedEncodingException e1) {
            e1.printStackTrace();
        }
*/

        // 取出上传对象, 过滤出文件对象
        Collection<Part> parts;
        try {
            parts = request.getParts();

            UploadValidImage uploadValidImage = new UploadValidImage();
            int addup = 0;  // 由于每商品存在多张图片, 设置标志变量
            CommodityDao commodityDao = CommonTools.getCommodityDao(contextPath);
            for (Part part : parts) {
                // 遍历所有上传信息(含文件或文本)
                String contDisp;
                if (null != part && null != part.getContentType()) {
                    // 如果上传的对象为文件
                    contDisp = part.getHeader("content-disposition");
                    ++addup;
                    // 当前商品的图片
                    uploadValidImage.appendImage(contDisp);
                    String uploadRealFolder = (contextPath + uploadValidImage.getImageFolderPath());
                    CommonTools.makePathDirs(uploadRealFolder);  // 在磁盘上创建上传文件夹
                    String uploadRealPath = uploadRealFolder + uploadValidImage.getLastImageName();
//                    System.out.println(uploadRealPath);
                    // 上传文件
                    part.write(uploadRealPath);
                    if (addup == imgUCPerCmdt) {
                        // 当前商品图片已上传完毕
                        addup = 0;
                        System.out.println("修改数据库数据:" + uploadValidImage.getCmdtSN());
                        // 修改数据库数据
                        // 获得数据库操作的DAO
                        Commodity commodity = commodityDao.getByBarCode(uploadValidImage.getCmdtSN());
                        if (null == commodity) {
                            // 出错啦
                            resultJson.put(Const.JS_P_ERRINFO, "没有从数据库中取到商品信息");
                            return;
                        }
                        commodity.setImagePath(uploadValidImage.getLongImageNames());   // 修改图片路径名
                        commodityDao.update(commodity); // 新的商品信息写入数据库

                        uploadValidImage.reset();
                    }

                } else {
                    String contentDisposition = part.getHeader("Content-Disposition");
                    System.out.println(contentDisposition);
                    System.out.println(request.getContentType());
                }
            }
        } catch (IOException e1) {
            e1.printStackTrace();
        } catch (ServletException e1) {
            e1.printStackTrace();
        }

        resultJson.put("resultInfo", "上传成功");
        PrintWriter out = response.getWriter();
        out.print(resultJson);
    }


    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }
}
